package com.whatech.mall.order.interceptor;

import com.whatech.mall.common.jwt.JwtException;
import com.whatech.mall.common.jwt.JwtOperator;
import com.whatech.mall.common.jwt.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微服务间通信JWT校验拦截器。
 */
@Slf4j
@Component
public class MsJwtValidateInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private JwtOperator jwtOperator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        if (jwtProperties == null
                || jwtOperator == null
                || !jwtProperties.isMsJwtEnabled()
                || StringUtils.isEmpty(jwtProperties.getMsJwtHeader())) {
            return true;
        }

        // 校验 JWT Header
        String jwtToken = request.getHeader(jwtProperties.getMsJwtHeader());
        if (StringUtils.isEmpty(jwtToken)) {
            throw new JwtException("No jwt header found inter-MicroService.");
        }

        return jwtOperator.validateToken(jwtToken);
    }
}
